<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/4/17
 * Time: 10:22
 */

namespace app\service\traits;

use app\admin\model\AdminMenu;
use app\company\model\CompanyMenu;
use app\company\model\CompanyRoleMenu;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use app\admin\model\AdminRoleMenu;

trait Menu
{
    /**
     * 获取树状菜单列表
     * @param $menuList
     * @param int $parentId
     * @return array
     */
    protected function getTreeData($menuList, int $parentId = 0): array
    {
        $data = [];
        foreach ($menuList as $key => $item) {
            if ($item['parent_id'] == $parentId) {
                $children = $this->getTreeData($menuList, (int)$item['id']);
                !empty($children) && $item['children'] = $children;
                $data[] = $item;
                unset($menuList[$key]);
            }
        }
        return $data;
    }

    /**
     * 获取用户菜单
     * @param  $userModel
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function getUserAuth($userModel): array
    {
        $appName = app('http')->getName();
        if($appName == 'admin') {
            $roles = $userModel->AdminUserRoles()->column('admin_role_id');
            $menus = AdminRoleMenu::whereIn('admin_role_id',$roles)->column('admin_menu_id');
            return $this->getTreeData(AdminMenu::whereIn('id',$menus)->select());
        }
        if($appName == 'company'){
            $roles = $userModel->companyUserRoles()->column('company_role_id');
            $menus = CompanyRoleMenu::whereIn('company_role_id',$roles)->column('company_menu_id');
            return $this->getTreeData(CompanyMenu::whereIn('id',$menus)->select());
        }
        return [];
    }
}